<template>
  <div style="padding: 20px">
    <h3 class="title">
      <span>当前谈案室：{{ roomNum }}号谈案室</span>
      <el-button type="primary" icon="el-icon-refresh-right" size="mini" @click="onRefresh">数据刷新</el-button>
    </h3>

    <div class="select-visit">
      <el-select v-model="visit_id" placeholder="请选择上门数据" style="width: 100%">
        <el-option v-for="item in visitList" :key="item.id" :label="`${item.selectText}`" :value="item.id"> </el-option>
      </el-select>
      <div class="visit-desc" v-if="visit_id">
        <div class="visit-item">
          <div class="label">访客姓名：</div>
          <div class="value">{{ selectVisit.name }}</div>
        </div>
        <div class="visit-item">
          <div class="label">访客手机：</div>
          <div class="value">{{ selectVisit.mobile }}</div>
        </div>
        <div class="visit-item">
          <div class="label">上门时间：</div>
          <div class="value">{{ selectVisit.confirm_time }}</div>
        </div>
        <div class="visit-item">
          <div class="label">大致案情：</div>
          <div class="value">{{ selectVisit.remark }}</div>
        </div>
      </div>
    </div>
    <div class="select-user">
      <el-select v-model="user_id" placeholder="请选择谈案顾问" filterable style="width: 100%">
        <el-option v-for="item in userList" :key="item.id" :label="item.realname" :value="item.id"> </el-option>
      </el-select>
    </div>

    <!-- <div style="font-size: 14px">
      <h3>录音时长：{{ recorder && recorder.duration.toFixed(4) }}</h3>
      <br />
      <el-button type="primary" @click="handleStart">开始录音</el-button>
      <el-button type="info" @click="handlePause">暂停录音</el-button>
      <el-button type="success" @click="handleResume">继续录音</el-button>
      <el-button type="warning" @click="handleStop">停止录音</el-button>
      <br />
      <br />
      <h3>
        播放时长：{{ recorder && (playTime > recorder.duration ? recorder.duration.toFixed(4) : playTime.toFixed(4)) }}
      </h3>
      <br />
      <el-button type="primary" @click="handlePlay">播放录音</el-button>
      <el-button type="info" @click="handlePausePlay">暂停播放</el-button>
      <el-button type="success" @click="handleResumePlay">继续播放</el-button>
      <el-button type="warning" @click="handleStopPlay">停止播放</el-button>
      <el-button type="error" @click="handleDestroy">销毁录音</el-button>
      <el-button type="primary" @click="uploadRecord">上传</el-button>
    </div> -->

    <div class="footer-box" v-if="visit_id && user_id">
      <div class="time-box">
        {{ recorder && recorder.duration.toFixed(2) }}
      </div>
      <div class="button-box">
        <div class="cancel-box" v-if="recordStatus != 0" @click="handleDestroy()">
          <i class="el-icon-close" style="font-size: 30px"></i>
          <div>取消</div>
        </div>
        <div class="play-box" @click="onClick">
          <i
            class="el-icon-video-play"
            style="font-size: 30px; color: red"
            v-if="recordStatus == 0 || recordStatus == 2 || recordStatus == 3"
          ></i>
          <i class="el-icon-video-pause" style="font-size: 30px; color: red" v-if="recordStatus == 1"></i>
        </div>
        <div class="confirm-box" v-if="recordStatus != 0" @click="uploadRecord">
          <i class="el-icon-check" style="font-size: 30px"></i>
          <div>完成录音</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Recorder from 'js-audio-recorder'
// eslint-disable-next-line
import { todayList, getUser, saveRecord, setStart } from '@/api/common.js'
// eslint-disable-next-line
import OSS from 'ali-oss'
// eslint-disable-next-line
import moment from 'moment'
import lamejs from 'lamejs'

export default {
  name: 'RecordPage',
  data() {
    return {
      companyId: localStorage.getItem('companyId'),
      roomNum: localStorage.getItem('roomNum'),
      recorder: null,
      playTime: 0,
      timer: null,
      src: null,

      // 上门登记数据
      visitList: [],
      visit_id: '',
      selectVisit: {},
      // 谈案顾问数据
      oldUserList: [],
      userList: [],
      user_id: '',
      selectUser: {},

      recordStatus: 0
    }
  },
  created() {
    // 若未设置公司
    if (!localStorage.getItem('companyId')) {
      this.$router.replace('/company')
      return
    }
    // 若未设置谈案室
    if (!localStorage.getItem('roomNum')) {
      this.$router.replace('/room')
      return
    }

    this.getUser()
    this.getList()
    this.recorder = new Recorder({
      sampleBits: 8, // 采样位数，支持 8 或 16，默认是16
      sampleRate: 8000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
      numChannels: 1 // 声道，支持 1 或 2， 默认是1
      // compiling: false,(0.x版本中生效,1.x增加中)  // 是否边录边转换，默认是false
    })
  },
  mounted() {},
  methods: {
    getList() {
      this.$loading()
      todayList({
        room: this.roomNum,
        str_id: this.companyId
      })
        .then(res => {
          this.visitList = res.data
          if (res.data.length == 1) {
            // 只有一条数据默认选中
            this.selectVisit = res.data[0]
            this.visit_id = res.data[0].id
          }
        })
        .finally(() => {
          this.$loading().close()
        })
    },
    getUser() {
      getUser({
        str_id: this.companyId
      }).then(res => {
        this.oldUserList = res.data
        this.userList = res.data
      })
    },
    onClick() {
      if (this.recordStatus == 0) {
        // 开始录音
        this.handleStart()
      } else if (this.recordStatus == 1) {
        // 暂停录音
        this.handlePause()
      } else if (this.recordStatus == 2) {
        // 继续录音
        this.handleResume()
      }
    },
    // 开始录音
    handleStart() {
      this.recorder = new Recorder()
      Recorder.getPermission().then(
        () => {
          console.log('开始录音')
          this.recorder.start() // 开始录音
          this.recordStatus = 1 // 录音中
          // this.$loading({
          //   lock: true,
          //   text: '设置开始谈案，录音功能启动中'
          // })
          // setStart({
          //   user_id: this.user_id,
          //   visit_id: this.visit_id
          // })
          //   .then(res => {
          //     if (res.code == 200) {
          //       console.log('开始录音')
          //       this.recorder.start() // 开始录音
          //       this.recordStatus = 1 // 录音中
          //     } else {
          //       this.$message({
          //         message: res.msg || '谈案状态设置失败',
          //         type: 'error'
          //       })
          //     }
          //   })
          //   .finally(() => {
          //     this.$loading().close()
          //   })
        },
        error => {
          this.$message({
            message: '请先允许该网页使用麦克风',
            type: 'info'
          })
          console.log(`${error.name} : ${error.message}`)
        }
      )
    },
    handlePause() {
      console.log('暂停录音')
      this.recorder.pause() // 暂停录音
      this.recordStatus = 2 // 已暂停
    },
    handleResume() {
      console.log('恢复录音')
      this.recorder.resume() // 恢复录音
      this.recordStatus = 1 // 录音中
    },
    handleStop() {
      console.log('停止录音')
      this.recorder.stop() // 停止录音
      this.recordStatus = 3 // 已停止
    },
    handlePlay() {
      console.log('播放录音')
      console.log(this.recorder)
      this.recorder.play() // 播放录音

      // 播放时长
      this.timer = setInterval(() => {
        try {
          this.playTime = this.recorder.getPlayTime()
        } catch (error) {
          this.timer = null
        }
      }, 100)
    },
    handlePausePlay() {
      console.log('暂停播放')
      this.recorder.pausePlay() // 暂停播放

      // 播放时长
      this.playTime = this.recorder.getPlayTime()
      this.time = null
    },
    handleResumePlay() {
      console.log('恢复播放')
      this.recorder.resumePlay() // 恢复播放

      // 播放时长
      this.timer = setInterval(() => {
        try {
          this.playTime = this.recorder.getPlayTime()
        } catch (error) {
          this.timer = null
        }
      }, 100)
    },
    handleStopPlay() {
      console.log('停止播放')
      this.recorder.stopPlay() // 停止播放

      // 播放时长
      this.playTime = this.recorder.getPlayTime()
      this.timer = null
    },
    handleDestroy(msg = '') {
      if (msg == '') msg = '取消录音将重置当前页面，您是否了解清楚？'
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log('销毁实例')
          this.recorder.destroy() // 销毁实例
          this.timer = null
          this.src = ''
          this.recordStatus = 0
          this.user_id = ''
          this.visit_id = ''
          this.getList()
          this.getUser()
        })
        .catch(() => {
          // on cancel
        })
    },
    uploadRecord() {
      if (this.recorder == null || this.recorder.duration === 0) {
        this.$message({
          message: '请先录音',
          type: 'error'
        })
        return false
      }
      this.recorder.pause() // 暂停录音
      this.timer = null
      console.log('上传录音') // 上传录音

      const blob = this.recorder.getWAV() // 获取wav格式音频数据
      const newbolb = this.convertToMp3(blob)
      // const newbolb = new Blob([blob], { type: 'audio/mp3' })
      // 配置你的OSS客户端
      const client = new OSS({
        region: 'oss-cn-beijing',
        accessKeyId: 'LTAI5t7nvBiE1bBDAQpXoS4j',
        accessKeySecret: 'Ig1kgCV46TJ5FBwWPGYZKgZGqGZdJW',
        bucket: 'lianghe'
      })
      let fileName = 'RecordApp/' + moment().format('YYYYMMDD') + '/' + this.generateNonceStr(32) + '.mp3' //文件名

      // 上传Blob文件
      client
        .put(fileName, newbolb)
        .then(({ res }) => {
          console.log('File uploaded successfully', res.statusCode)
        })
        .catch(err => {
          console.error('File upload failed', err)
        })

      // const formData = new FormData()
      // const blob = this.recorder.getWAVBlob() // 获取wav格式音频数据
      // // 此处获取到blob对象后需要设置fileName满足当前项目上传需求，其它项目可直接传把blob作为file塞入formData
      // const newbolb = new Blob([blob], { type: 'audio/wav' })
      // const fileOfBlob = new File([newbolb], new Date().getTime() + '.wav')
      // formData.append('file', fileOfBlob)
      // const url = window.URL.createObjectURL(fileOfBlob)
      // this.src = url
      // console.log(this.src)
      // const axios = require('axios')
      // axios.post(url, formData).then(res => {
      //   console.log(res.data.data[0].url)
      // })
    },
    onRefresh() {
      if (this.recordStatus != 0) {
        this.handleDestroy('正在录音刷新将重置当前页面，您是否了解清楚？')
      } else {
        this.getList()
        this.getUser()
      }
    },
    // 随机码生成
    generateNonceStr(length = 16) {
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
      const maxPos = chars.length
      let nonceStr = ''
      for (let i = 0; i < length; i++) {
        nonceStr += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return nonceStr
    },
    convertToMp3(wavDataView) {
      // 获取wav头信息
      const wav = lamejs.WavHeader.readHeader(wavDataView) // 此处其实可以不用去读wav头信息，毕竟有对应的config配置
      const { channels, sampleRate } = wav
      const mp3enc = new lamejs.Mp3Encoder(channels, sampleRate, 128)
      // 获取左右通道数据
      const result = this.recorder.getChannelData()
      const buffer = []
      const leftData = result.left && new Int16Array(result.left.buffer, 0, result.left.byteLength / 2)
      const rightData = result.right && new Int16Array(result.right.buffer, 0, result.right.byteLength / 2)
      const remaining = leftData.length + (rightData ? rightData.length : 0)
      const maxSamples = 1152
      for (let i = 0; i < remaining; i += maxSamples) {
        const left = leftData.subarray(i, i + maxSamples)
        let right = null
        let mp3buf = null
        if (channels === 2) {
          right = rightData.subarray(i, i + maxSamples)
          mp3buf = mp3enc.encodeBuffer(left, right)
        } else {
          mp3buf = mp3enc.encodeBuffer(left)
        }
        if (mp3buf.length > 0) {
          buffer.push(mp3buf)
        }
      }
      const enc = mp3enc.flush()
      if (enc.length > 0) {
        buffer.push(enc)
      }
      return new Blob(buffer, { type: 'audio/mp3' })
    }
  }
}
</script>

<style lang="scss" scoped>
.title {
  display: flex;
  align-items: center;
  justify-content: center;
  .el-button {
    margin-left: 10px;
  }
}
.visit-desc {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-top: 10px;

  .visit-item {
    display: flex;
    align-items: center;

    .label {
      color: #555555;
    }

    .value {
      color: #007aff;
    }
  }

  .visit-item:not(:first-child) {
    margin-left: 10px;
  }
}
.select-user {
  margin-top: 10px;
}
.footer-box {
  width: 100%;
  bottom: 25%;
  position: fixed;

  .time-box {
    height: 80px;
    line-height: 80px;
    text-align: center;
  }

  .button-box {
    display: flex;
    align-items: center;
    justify-content: space-evenly;

    .cancel-box {
      color: #f0ad4e;
      text-align: center;
    }

    .play-box {
      width: 130px;
      height: 130px;
      border: 2px solid #c8c7cc;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .confirm-box {
      color: #007aff;
      text-align: center;
    }
  }
}
</style>
